﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace AccessControl.Video.Rtp
{
	/// <summary>
	/// Represents RTP packet
	/// </summary>
	/// <remarks></remarks>
	class RtpPacket
	{
		#region Fields

		protected byte[] _payload;

		#endregion

		#region Public Constructor

		/// <summary>
		/// Initializes a new instance of the <see cref="RtpPacket"/> class.
		/// </summary>
		/// <param name="bytes">The bytes.</param>
		/// <remarks></remarks>
		public RtpPacket(byte[] bytes)
		{
			/* Get the first two bytes */
			byte version = (byte)(bytes[0] >> 6);
			byte padding = (byte)(0x1 & (bytes[0] >> 5));
			byte extension = (byte)(0x1 & (bytes[0] >> 4));
			byte csrc_count = (byte)(0x1F & (bytes[0]));
			IsLastPacketInFrame = ((bytes[1] >> 7) == 1);
			byte payload_type = (byte)(bytes[1] & 0x7f);
			/* Get the sequence number */
			SequenceNumber = (uint)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(bytes, 2));
			/* Get the timestamp */
			Timestamp = (uint)IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(bytes, 4));
			/* Get the SSRC */
			SSRC = (uint)IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(bytes, 8));
			/* And the rest is payload */
			Payload = new byte[bytes.Length - 12];
			Array.Copy(bytes, 12, Payload, 0, Payload.Length);
		}

		#endregion

		#region Public Properties

		/// <summary>
		/// Gets a value indicating whether this instance is last packet in frame.
		/// </summary>
		/// <remarks></remarks>
		public bool IsLastPacketInFrame 
		{ 
			get; private set; 
		}

		/// <summary>
		/// Gets the sequence number.
		/// </summary>
		/// <remarks></remarks>
		public uint SequenceNumber 
		{ 
			get; private set; 
		}

		/// <summary>
		/// Gets the timestamp.
		/// </summary>
		/// <remarks></remarks>
		public uint Timestamp 
		{ 
			get; private set; 
		}

		/// <summary>
		/// Gets the SSRC.
		/// </summary>
		/// <remarks></remarks>
		public uint SSRC 
		{ 
			get; private set; 
		}

		/// <summary>
		/// Gets the payload.
		/// </summary>
		/// <remarks></remarks>
		public byte[] Payload 
		{
			get { return _payload; }
			protected set
			{
				_payload = value;
			}
		}

		#endregion
	}
}
